/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.felipecsl.asymmetricgridview;

import ohos.utils.Parcel;
import ohos.utils.Sequenceable;

import java.util.Stack;

/**
 * 对象池
 *
 * @param <T> 对象泛型
 * @since 2021-04-02
 */
class ObjectPool<T> implements Sequenceable {
    Stack<T> stack = new Stack<>();
    PoolObjectFactory<T> factory;
    PoolStats stats;

    protected ObjectPool(Parcel in) {
    }

    ObjectPool() {
        stats = new PoolStats();
    }

    ObjectPool(PoolObjectFactory<T> factory) {
        this.factory = factory;
    }

    @Override
    public boolean marshalling(Parcel parcel) {
        return false;
    }

    @Override
    public boolean unmarshalling(Parcel parcel) {
        return false;
    }

    /**
     * 池状态
     *
     * @since 2021-04-02
     */
    static class PoolStats {
        int size = 0;
        int hits = 0;
        int misses = 0;
        int created = 0;

        String getStats(String name) {
            return String.format("%s: size %d, hits %d, misses %d, created %d", name, size, hits,
                misses, created);
        }
    }

    T get() {
        if (!stack.isEmpty()) {
            stats.hits++;
            stats.size--;
            return stack.pop();
        }

        stats.misses++;

        T object = factory != null ? factory.createObject() : null;

        if (object != null) {
            stats.created++;
        }

        return object;
    }

    void put(T object) {
        stack.push(object);
        stats.size++;
    }

    void clear() {
        stats = new PoolStats();
        stack.clear();
    }

    String getStats(String name) {
        return stats.getStats(name);
    }
}